<template>
  <view class="wrap">
    <view class="listWrap" v-if="list && list.length > 0">
      <view class="item" v-for="(item, index) in list" :key="index">
        <view class="top">
          <text>{{
            item.createTime
              ? transformTimeTwo(
                  new Date(item.createTime.replace(/\-/g, '/')).getTime(),
                  ''
                ).replace(/\//g, '-')
              : ''
          }}</text>
          <text
            :class="[
              'state',
              item.payState == 'SUCCESS' ? 'on' : item.payState == 'PROGRESS' ? 'active' : ''
            ]"
            >{{
              item.payState == 'SUCCESS'
                ? '已完成'
                : item.payState == 'CLOSE'
                ? '已取消'
                : item.payState == 'REFUNDED'
                ? '已退款'
                : item.payState == 'PROGRESS'
                ? '待支付'
                : ''
            }}</text
          >
        </view>
        <view class="min">
          <view class="serve">
            <text>{{ item.tradeName }}</text>
            <text class="num">¥{{ (item.amount / 100).toFixed(2) }}</text>
          </view>
          <view class="user">
            <text class="name">会员使用人：</text>
            <text class="nick">{{ item.patName }}</text>
          </view>
          <view class="user">
            <text class="name">服务有效期：</text>
            <text class="nick" v-if="item.payState == 'SUCCESS'"
              >{{
                item.payTime
                  ? transformTimeTwo(
                      new Date(item.payTime.replace(/\-/g, '/')).getTime(),
                      'date'
                    ).replace(/\//g, '-')
                  : ''
              }}
              -
              {{
                item.expiredTime
                  ? transformTimeTwo(
                      new Date(item.expiredTime.replace(/\-/g, '/')).getTime(),
                      'date'
                    ).replace(/\//g, '-')
                  : ''
              }}</text
            >
          </view>
          <view class="pay" v-if="item.payState == 'PROGRESS'">
            <text class="btn" @tap="immediatelyPay(item)">去支付</text>
          </view>
        </view>
      </view>
    </view>
    <view class="nodate" v-else>
      <img class="img" src="https://ainengli.hzjrsw.com/jkhx/noData.png" alt="" />
      <view class="nodate_text">
        <text class="name">暂无数据</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onShow, onUnload } from '@dcloudio/uni-app'
import { transformTimeTwo } from '@/utils/hmm'
import { orderList, payByOrderNo, orderStatus } from '@/api/hmm'
import { base_info } from '@/api/moreMessage'
import store from '@/store'
const state = reactive({
  timeQuestions: null
})
const getUserId = ref({})
const list = ref([])
const bizOrderNo = ref('')
const userInfo = ref({})
const userInfoNew = ref({})
const isstop = ref(false)
onShow(() => {
  getUserId.value = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).userId
    : ''
  userInfo.value = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}
  userInfoNew.value = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo'))
    : {}
  init()
})
onUnload(() => {
  isstop.value = false
  clearInterval(state.timeQuestions)
  state.timeQuestions = null
})
const init = () => {
  uni.showLoading({
    title: '加载中'
  })
  let param = getUserId.value
  orderList(param).then((res) => {
    if (isstop.value == false) {
      uni.hideLoading()
    }
    if (res.code == 0) {
      list.value = res.data && res.data.length > 0 ? res.data : []
    }
  })
}
const immediatelyPay = (item) => {
  let param = {
    bizOrderNo: item.bizOrderNo
  }
  uni.showLoading({
    title: '加载中'
  })
  payByOrderNo(param).then((res) => {
    uni.hideLoading()
    let payParam = JSON.parse(res.data.payBody)
    bizOrderNo.value = res.data.bizOrderNo
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: payParam.timeStamp,
      nonceStr: payParam.nonceStr,
      package: payParam.package,
      signType: payParam.signType,
      paySign: payParam.paySign,
      success: function (res) {
        isstop.value = true
        loopTime()
        console.log('success:' + JSON.stringify(res))
      },
      fail: function (err) {
        isstop.value = false
        uni.hideLoading()
        // uni.showToast({
        //   title: '支付失败,请重试',
        //   icon: 'error',
        //   duration: 2000
        // })
        console.log('fail:' + JSON.stringify(err))
      }
    })
  })
}
const loopTime = () => {
  let s = 0
  state.timeQuestions = setInterval(() => {
    s++
    if (s >= 2) {
      s = 0
      orderStatusFun()
    }
  }, 1000)
}
const orderStatusFun = () => {
  let param = bizOrderNo.value
  orderStatus(param).then((res) => {
    if (res.data.payState == 'PROGRESS') {
    } else if (res.data.payState == 'SUCCESS') {
      let params = {
        userId: userInfoNew.value.userId,
        empi: userInfo.value.empi
      }
      base_info(params).then((res) => {
        const info = Object.assign({}, JSON.parse(uni.getStorageSync('userInfo')))
        info.patientInfo = res.data
        store.commit('SET_USERINFO', info)
        clearInterval(state.timeQuestions)
        state.timeQuestions = null
        uni.showToast({
          title: '支付成功',
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          isstop.value = false
          init()
        }, 2000)
      })
    } else if (res.data.payState == 'REFUNDED' || res.data.payState == 'CLOSE') {
      //   uni.showToast({
      //     title: '支付失败',
      //     icon: 'none'
      //   })
      clearInterval(state.timeQuestions)
      state.timeQuestions = null
    }
  })
}
</script>

<style lang="scss" scoped>
.wrap {
  .listWrap {
    padding-bottom: 32rpx;
    display: inline-block;
    width: calc(100% - 64rpx);
    margin-left: 32rpx;
    .item {
      background: #fff;
      border-radius: 12rpx;
      padding: 0 32rpx 24rpx;
      font-size: 28rpx;
      color: #666;
      margin-top: 24rpx;
      .top {
        height: 88rpx;
        line-height: 88rpx;
        position: relative;
        border-bottom: 1rpx solid #e5e6eb;
        .state {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          right: 0;
          height: 40rpx;
          line-height: 40rpx;
          padding: 0 16rpx;
          background: #f5f5f5;
          border: 1rpx solid #f5f5f5;
          font-size: 24rpx;
          color: #666;
          border-radius: 4rpx;
          &.on {
            color: #00d1b6;
            border-color: rgba(0, 209, 182, 0.1);
            background: rgba(0, 209, 182, 0.1);
          }
          &.active {
            color: #ff503d;
            border-color: rgba(255, 80, 61, 0.1);
            background: rgba(255, 80, 61, 0.1);
          }
        }
      }
      .min {
        .serve {
          margin-top: 24rpx;
          font-size: 36rpx;
          color: #222;
          font-weight: 700;
          position: relative;
          .num {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            right: 0;
            font-size: 36rpx;
            color: #ff503d;
          }
        }
        .user {
          margin-top: 24rpx;
          .name {
            display: inline-block;
            vertical-align: middle;
          }
          .nick {
            display: inline-block;
            vertical-align: middle;
            color: #222;
          }
        }
        .pay {
          border-top: 1rpx solid #e5e6eb;
          margin-top: 24rpx;
          height: 80rpx;
          position: relative;
          .btn {
            display: block;
            position: absolute;
            top: 24rpx;
            right: 0rpx;
            padding: 13rpx 32rpx;
            background: #ff503d;
            color: #fff;
            font-size: 24rpx;
            border-radius: 30rpx;
          }
        }
      }
    }
  }
  .nodate {
    text-align: center;
    .img {
      display: inline-block;
      width: 320rpx;
      height: 240rpx;
      margin-top: 240rpx;
    }
    .nodate_text {
      .name {
        display: block;
        font-size: 28rpx;
        color: #666;
        text-align: center;
        margin-top: 10rpx;
      }
    }
  }
}
</style>
